import 'dart:collection';
import 'dart:convert';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_html/style.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:group_button/group_button.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:shop/config/config.dart';
import 'package:shop/http/HttpUtil.dart';
import 'package:shop/route/my_route.dart';
import 'package:shop/shop/life/LjgmOrder.dart';
import 'package:shop/shop/life/MyYuYue.dart';
import 'package:shop/shop/life/ServiceDetail.dart';

import 'GoodsDetail.dart';
import 'MerchantPage.dart';
import 'ServiceIndexPage.dart';

class MyShouCang extends StatefulWidget {
  MyShouCang({Key key}) : super(key: key);

  @override
  _MyShouCang createState() => _MyShouCang();
}

class _MyShouCang extends State<MyShouCang> {
  // 构造方法
  _MyShouCang() {
    _onLoading();
  }

  final SlidableController slidableController = SlidableController(); // 滑动控制器
  List shouCangList = []; //用户收藏商家和用户集合
  int page = 1;           //页数
  String userId;          //用户ID

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }
  // 上拉加载控制器
  RefreshController _refreshController = RefreshController(initialRefresh: false);
  void _onRefresh() async{
    // monitor network fetch
    // await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use refreshFailed()
    _refreshController.refreshCompleted();
  }

  // 加载数据的函数
  void _onLoading() async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    userId = prefs.getString("userId");
    var x = await HttpUtil().get("/waimai/mCollect/getUserCollect?limit=10&page=${page}&userId="+userId);
    page++;
    if(x['code']==200){
      shouCangList.addAll(x['data']);
      if(x['data'].length<1){
        _refreshController.loadNoData();
        return;
      }
    }
    setState(() {
      setState(() {});
      _refreshController.loadComplete();
    });
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 464, height: 820);
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        automaticallyImplyLeading: false,
        title: Text("我的收藏"),
      ),
      body: SmartRefresher(
        enablePullDown: false,
        enablePullUp: true,
        header: WaterDropHeader(),
        footer: CustomFooter(
          builder: (BuildContext context,LoadStatus mode){
            Widget body ;
            if(mode==LoadStatus.idle){
              body =  Text("上拉加载");
            }
            else if(mode==LoadStatus.loading){
              body =  CupertinoActivityIndicator();
            }
            else if(mode == LoadStatus.failed){
              body = Text("加载失败！点击重试！");
            }
            else if(mode == LoadStatus.canLoading){
              body = Text("松手,加载更多!");
            }
            else{
              body = Text("没有更多数据了!");
            }
            return Container(
              height: 55.0,
              child: Center(child:body),
            );
          },
        ),
        controller: _refreshController,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child: ListView.builder(
          itemBuilder: (c, i) => Card(child: _showShouCang(shouCangList[i])),
          itemExtent: 100.0,
          itemCount: shouCangList.length,
        ),
      ),
    );
  }

  //显示收藏商家或商品
  _showShouCang(item){
    return GestureDetector(
      child: Container(
        child: Slidable(
          controller: slidableController,
          actionPane: SlidableDrawerActionPane(),
          actionExtentRatio: 0.25,
          child: Container(
            color: Colors.white,
            child: ListTile(
              leading: CircleAvatar(
                // backgroundColor: Colors.indigoAccent,
                backgroundColor: Colors.white,
                // child: CachedNetworkImage(imageUrl: "http://bpic.588ku.com/element_pic/17/12/16/0ffbd64366f99a865fd4d98cea57db55.jpg",),
                child: CachedNetworkImage(imageUrl: item['type']==0 ? Config.getInstance().getHost()+item['merchant']['picture'] : Config.getInstance().getHost()+item['mgoods']['gimages'],),
                foregroundColor: Colors.white,
              ),
              title: Text(item['type']==0 ? item['merchant']['mname'] : item['mgoods']['gname'],maxLines: 1,overflow: TextOverflow.ellipsis,),
              subtitle: Text(item['type']==0 ? item['merchant']['jianjie'] : item['mgoods']['jianjie'],maxLines: 2,overflow: TextOverflow.ellipsis,),
            ),
          ),
          secondaryActions: <Widget>[
            IconSlideAction(
              caption: '详情',
              color: Colors.black45,
              icon: Icons.more_horiz,
              onTap: () {
                int shoucangType = item['type'];
                int merchantType = 0;
                if(item['type']==0){
                  merchantType = item['merchant']['isFuwu'];
                }else{
                  merchantType = item['mgoods']['mgoodsType']['merchantType']['type'];
                }
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    //全部跳店铺页面
                    builder:(context)=>shoucangType==0 ? (merchantType==0 ? MerchantPage(merchantId: item['mid'],merchantTypeId: item['mtypeId'],) : ServiceIndexPage(mId: item['mid']))
                                            : (merchantType==0 ? MerchantPage(merchantId: item['mgoods']['merchant']['id'],merchantTypeId: item['mgoods']['mgoodsType']['merchantType']['id'],) : ServiceIndexPage(mId: item['mgoods']['merchant']['id'])),
                    //店铺收藏跳店铺页面，商品收藏跳商品详情页
                    // builder:(context)=>shoucangType==0 ? (merchantType==0 ? MerchantPage(merchantId: item['mid'],merchantTypeId: item['mtypeId'],) : ServiceIndexPage(mId: item['mid']))
                    //     : (merchantType==0 ? GoodsDetail(gid: item['gid'],cartList: [],cartSize: 0,merchantName: item['mgoods']['merchant']['mname'],merchantId: item['mgoods']['merchant']['id'],goodsTypeList: [],zongjia: 0.00,zongdabaofei: 0.00,) : ServiceDetail(gid: item['gid'])),
                  )
                );
              },
            ),
            IconSlideAction(
              caption: '删除',
              color: Colors.red,
              icon: Icons.delete,
              onTap: () async {
                var map = new HashMap<String,dynamic>();
                map['mid']=item['mid'];map['type']=item['type'];map['userId']=userId;map['mtypeId']=item['mtypeId'];map['gid']=item['gid'];map['id']=item['id'];
                Response response = await HttpUtil().post("waimai/mCollect/collect",map);
                var x = json.decode(response.toString());
                if(x['code']==200){
                  shouCangList.remove(item);
                }
                Fluttertoast.showToast(
                    msg: x['msg'],
                    toastLength: Toast.LENGTH_SHORT,
                    gravity: ToastGravity.BOTTOM,
                    timeInSecForIosWeb: 1,
                    backgroundColor: Colors.black45,
                    textColor: Colors.white,
                    fontSize: 16.0
                );
                setState(() {

                });
              },
            ),
          ],
        ),
      ),
      onTap: (){

      },
    );
  }

  // @override
  // Widget build(BuildContext context) {
  //   ScreenUtil.init(context, width: 464, height: 820);
  //   return new Scaffold(
  //     appBar: AppBar(
  //       title: Text("我的收藏"),
  //     ),
  //     body: Column(
  //       children: [
  //         Slidable(
  //           controller: slidableController,
  //           actionPane: SlidableDrawerActionPane(),
  //           actionExtentRatio: 0.25,
  //           child: Container(
  //             color: Colors.white,
  //             child: ListTile(
  //               leading: CircleAvatar(
  //                 backgroundColor: Colors.indigoAccent,
  //                 child: CachedNetworkImage(imageUrl: "http://bpic.588ku.com/element_pic/17/12/16/0ffbd64366f99a865fd4d98cea57db55.jpg",),
  //                 foregroundColor: Colors.white,
  //               ),
  //               title: Text('泰式按摩金三角分店'),
  //               subtitle: Text('金三角大力发酒店旁'),
  //             ),
  //           ),
  //           secondaryActions: <Widget>[
  //             IconSlideAction(
  //               caption: '详情',
  //               color: Colors.black45,
  //               icon: Icons.more_horiz,
  //               onTap: () {
  //                 print("跳转到详情页面");
  //               },
  //             ),
  //             IconSlideAction(
  //               caption: '删除',
  //               color: Colors.red,
  //               icon: Icons.delete,
  //               onTap: () {
  //                 print("删除收藏");
  //               },
  //             ),
  //           ],
  //         ),
  //         Slidable(
  //           controller: slidableController,
  //           actionPane: SlidableDrawerActionPane(),
  //           actionExtentRatio: 0.25,
  //           child: Container(
  //             color: Colors.white,
  //             child: ListTile(
  //               leading: CircleAvatar(
  //                 backgroundColor: Colors.indigoAccent,
  //                 child: CachedNetworkImage(imageUrl: "http://bpic.588ku.com/element_pic/17/12/16/0ffbd64366f99a865fd4d98cea57db55.jpg",),
  //                 foregroundColor: Colors.white,
  //               ),
  //               title: Text('泰式按摩金三角分店'),
  //               subtitle: Text('金三角大力发酒店旁'),
  //             ),
  //           ),
  //           secondaryActions: <Widget>[
  //             IconSlideAction(
  //               caption: '详情',
  //               color: Colors.black45,
  //               icon: Icons.more_horiz,
  //               onTap: () {
  //                 MyRoute.push(MyYuYue());
  //               },
  //             ),
  //             IconSlideAction(
  //               caption: '删除',
  //               color: Colors.red,
  //               icon: Icons.delete,
  //               onTap: () {
  //                 print("删除收藏");
  //               },
  //             ),
  //           ],
  //         ),
  //
  //         Expanded(child: SmartRefresher(
  //           enablePullDown: false,
  //           enablePullUp: true,
  //           header: WaterDropHeader(),
  //           footer: CustomFooter(
  //             builder: (BuildContext context,LoadStatus mode){
  //               Widget body ;
  //               if(mode==LoadStatus.idle){
  //                 body =  Text("上拉加载");
  //               }
  //               else if(mode==LoadStatus.loading){
  //                 body =  CupertinoActivityIndicator();
  //               }
  //               else if(mode == LoadStatus.failed){
  //                 body = Text("加载失败！点击重试！");
  //               }
  //               else if(mode == LoadStatus.canLoading){
  //                 body = Text("松手,加载更多!");
  //               }
  //               else{
  //                 body = Text("没有更多数据了!");
  //               }
  //               return Container(
  //                 height: 55.0,
  //                 child: Center(child:body),
  //               );
  //             },
  //           ),
  //           controller: _refreshController,
  //           onRefresh: _onRefresh,
  //           onLoading: _onLoading,
  //           child: ListView.builder(
  //             itemBuilder: (c, i) => Card(child: _showGoods(shouCangList[i])),
  //             itemExtent: 100.0,
  //             itemCount: shouCangList.length,
  //           ),
  //         ),)
  //       ],
  //     )
  //   );
  // }

  // GestureDetector _showGoods(item){
  //   return GestureDetector(
  //     child: Container(
  //       child: Column(
  //         children: [
  //           Row(
  //            mainAxisAlignment: MainAxisAlignment.spaceBetween,
  //             children: [
  //               Text(item['merchant']['mname'],style: TextStyle(fontWeight: FontWeight.bold,fontSize: 22,color: Colors.red),),
  //               item['status']==0 ? Text("预约中",style: TextStyle(fontSize: 16,color: Colors.amberAccent),) : (item['status']==1 ? Text("已取消预约",style: TextStyle(fontSize: 16,color: Colors.red)) : Text("预约成功",style: TextStyle(fontSize: 16,color: Colors.green),))
  //             ],
  //           ),
  //         SizedBox(height: 10,),
  //         Row(
  //           mainAxisAlignment: MainAxisAlignment.spaceBetween,
  //           children: [
  //             Text(item['mgoods']['gname']),
  //             Text(item['createTime'],style: TextStyle(color: Colors.black),)
  //           ],
  //         ),],
  //       ),
  //     ),
  //     onTap: (){
  //
  //     },
  //   );
  // }

}
